<template>
  <div class="m-dashboard">
    <div class="g-content pb-0">
      <x-form ref="formRef" v-model:model="form" inline wrap label-placement="left" size="small">
        <n-form-item label="广告ID">
          <n-input v-model:value="form.adgroupId" size="small" placeholder="请输入账户ID" clearable></n-input>
        </n-form-item>
        <n-form-item label="广告名">
          <n-input v-model:value="form.adgroupName" size="small" placeholder="请输入账户名称" clearable></n-input>
        </n-form-item>
        <n-form-item label="账户主体">
          <n-select v-model:value="form.mdmName" size="small" placeholder="请选择" :options="companyList" clearable />
        </n-form-item>
        <n-form-item label="媒体账户">
          <n-select
            v-model:value="form.accountCode"
            size="small"
            placeholder="请选择"
            :options="accountOwnerList"
            clearable
          />
        </n-form-item>
        <n-form-item label="所属人员">
          <n-select
            v-model:value="form.accountId"
            label-field="accountName"
            value-field="accountId"
            size="small"
            placeholder="请选择"
            :options="accountList"
            clearable
          />
        </n-form-item>
        <n-form-item label="操作状态">
          <n-select
            v-model:value="form.configuredStatus"
            size="small"
            placeholder="请选择"
            :options="dictionary['GDT_CONFIGURED_STATUS']"
            clearable
          />
        </n-form-item>
        <n-form-item label="投放状态">
          <n-select
            v-model:value="form.systemStatus"
            size="small"
            placeholder="请选择"
            :options="dictionary['GDT_SYSTEM_STATUS']"
            clearable
          />
        </n-form-item>
        <n-form-item label="一键起量">
          <n-select
            v-model:value="form.autoAcquisitionEnabled"
            size="small"
            placeholder="请选择"
            :options="autoAcquisitionList"
            clearable
          />
        </n-form-item>
        <n-form-item label="余额情况">
          <n-select
            v-model:value="form.balanceStatus"
            size="small"
            placeholder="请选择"
            :options="balanceStatusList"
            clearable
          />
        </n-form-item>
        <n-form-item label="创建日期">
          <x-date-picker
            v-model:value="form.dateRange"
            style="width: 600px"
            type="daterange"
            clearable
            :actions="['confirm']"
            @update:value="handleSubmit"
          />
        </n-form-item>
        <n-form-item label="投放日期">
          <x-date-picker
            v-model:value="form.dateRange1"
            style="width: 600px"
            type="daterange"
            clearable
            :actions="['confirm']"
            @update:value="handleSubmit"
          />
        </n-form-item>
        <n-space>
          <x-button size="small" type="primary" @click="handleSubmit">查询</x-button>
          <x-button size="small" @click="handleRefresh">重置</x-button>
        </n-space>
      </x-form>
    </div>
    <div class="g-content">
      <div>
        <x-data-table
          ref="tableRef"
          v-model:immediate="immediate"
          v-model:checked-row-keys="checkedIds"
          :params="paginationParams"
          :columns="columns"
          :scroll-x="TableScrollX"
          :row-key="(row) => row.id"
          :export-action="exportAction"
          :export-name-prefix="exportName"
          row-class-name="text-sm"
          max-height="infinite"
          @update:sorter="handleSorterChange"
          @setData="getNowPageData"
        >
          <template #tableTitle>
            <div class="toolbars">
              <BatchOperation
                :checked-ids="checkedIds"
                :checked-data="checkedData"
                :type="'ad'"
                @success="handleReload"
                @closeChecked="closeChecked"
              />
            </div>
            <div class="flex">
              <div style="flex: 1"></div>
              <x-diy-column-draggable
                :key="diyColumnName"
                v-model:value="showColumnList"
                :button-size="'small'"
                :name="diyColumnName"
                :min="0"
                api="dictionary/columnList"
                :api-params="diyColumnParams"
                :default-value="columnDefaultValue"
              />
            </div>
          </template>
        </x-data-table>
      </div>
    </div>
    <AdGroupDetailModal v-if="adGroupModal.show" :modal-data="adGroupModal" />
  </div>
</template>

<script setup lang="ts">
  import { formatDate } from '@/utils'
  import { ref, computed, h, onMounted, reactive } from 'vue'
  import { XForm, XButton, XDataTable, XDiyColumnDraggable, XDatePicker } from '@/components'
  import { NFormItem, NSelect, NText, NInput, NSpace, useMessage, NSwitch } from 'naive-ui'
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from '@/store'
  import { useDictionary } from '@/hooks'
  import { accountList } from '@/api/system'
  import { gdtAccountOwnerList } from '@/api/intelligent'
  import BatchOperation from '@/views/advertising/components/BatchOperation.vue'
  import AdGroupDetailModal from '@/views/advertising/components/AdGroupDetailModal.vue'
  const router = useRouter()
  const route = useRoute()
  const store = useStore()
  const message = useMessage()
  const { get: getDic, find: findDic } = useDictionary()

  getDic('GDT_CONFIGURED_STATUS,GDT_SYSTEM_STATUS')
  const dictionary = computed(() => store.getters.dictionary)

  const props = defineProps({
    dateRange: {
      type: Array,
      default: () => [Date.parse(new Date()), Date.parse(new Date())]
    }
  })
  const getProps = reactive(props)
  const adGroupModal = ref({
    show: false,
    row: null
  })
  const tableRef = ref(null)
  const formRef = ref(null)
  const accountCode = route.query.accountCode

  const form = ref({
    accountCode: route.query.accountCode,
    order: '',
    desc: null,
    adgroupId: null,
    adgroupName: null,
    mdmName: null,
    accountId: null,
    configuredStatus: 3,
    systemStatus: null,
    autoAcquisitionEnabled: null,
    balanceStatus: null,
    dateRange: null,
    dateRange1: null
  })
  const checkedIds = ref([])
  const nowData = ref([])
  const checkedData = computed(() => {
    return nowData.value.filter((item) => checkedIds.value.includes(item?.id))
  })
  const balanceStatusList = ref([
    {
      label: '查看为0的账户',
      value: 0
    },
    {
      label: '查看不为0的账户',
      value: 1
    }
  ])

  const autoAcquisitionList = ref([
    {
      label: '未开启',
      value: 0
    },
    {
      label: '开启',
      value: 1
    }
  ])
  const companyList = ref([])
  const accountList = ref([])
  const accountOwnerList = ref([])
  const immediate = ref(true)
  const diyColumnParams = ref({
    key: 'ADGROUP_REPORT'
  })
  // 自定义列
  const showColumnList = ref([])
  const diyColumnName = computed(() => {
    return 'ADGROUP_COLUMN'
  })
  const columnDefaultValue = ref(['account1'])
  const paginationParams = computed(() => {
    return {
      actions: 'intelligent/gdtAdgroupsList',
      data: {
        ...form.value,
        dateRange: null,
        dateRange1: null,
        startDate: getProps.dateRange?.[0] ? formatDate(getProps.dateRange?.[0]) : null,
        endDate: getProps.dateRange?.[1] ? formatDate(getProps.dateRange?.[1]) : null,
        createStartDate: form.value.dateRange ? formatDate(form.value.dateRange?.[0]) : null,
        createEndDate: form.value.dateRange ? formatDate(form.value.dateRange?.[1]) : null,
        beginStartDate: form.value.dateRange1 ? formatDate(form.value.dateRange1?.[0]) : null,
        beginEndDate: form.value.dateRange1 ? formatDate(form.value.dateRange1?.[1]) : null,
        columns: showColumnList.value?.toString()
      }
    }
  })
  const exportAction = computed(() => 'intelligent/adgroupsExport')
  const exportName = computed(() => {
    return `【广告】${formatDate(new Date(), 'yyyyMMddhhmmss')}`
  })
  const columns = computed(() => {
    const arr = [
      {
        title: '广告',
        key: 'adgroupName',
        fixed: 'left',
        width: 100,
        resizable: true,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(NText, {}, () => row.adgroupName),
            h(NText, {}, () => `ID：${row.adgroupId}`)
          ])
        }
      },
      {
        title: '操作',
        fixed: 'left',
        width: 100,
        key: 'operator',
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(XButton, { text: true, size: 'mini', type: 'primary', onClick: () => handleDetail(row) }, () => '详情'),
            h(
              XButton,
              { text: true, size: 'mini', type: 'primary', onClick: () => handleCreate(row) },
              () => '添加创意'
            ),
            h(XButton, { text: true, size: 'mini', type: 'primary', onClick: () => handleMedia(row) }, () => '查看创意')
          ])
        }
      },
      {
        title: '账户名称',
        key: 'accountName',
        width: 100,
        render(row: any) {
          return h(NSpace, {}, () => [
            h(NText, {}, () => row.accountName),
            h(NText, {}, () => `ID:${row.accountCode}`),
            h(NText, {}, () => `广告主行业:${row.systemIndustryName || '-'}`)
          ])
        }
      },
      {
        title: '投放日期',
        key: 'launchTime',
        width: 120
      },
      {
        title: '状态',
        key: 'systemStatusStr',
        width: 80
      },
      {
        title: '出价',
        key: 'bidAmount',
        sorter: true,
        width: 80
      },
      {
        title: '所属人员',
        key: 'ownerName',
        width: 100
      },
      {
        title: '日预算（元/天）',
        key: 'dailyBudget',
        sorter: true,
        width: 140
      },
      {
        title: '曝光次数',
        key: 'viewCount',
        sorter: true,
        width: 120
      },
      {
        title: '曝光人数',
        key: 'viewUserCount',
        sorter: true,
        width: 120
      },
      {
        title: '点击次数',
        key: 'validClickCount',
        sorter: true,
        width: 100
      },
      {
        title: '点击人数',
        key: 'clickUserCount',
        sorter: true,
        width: 100
      },
      {
        title: '点击均价',
        key: 'cpc',
        sorter: true,
        width: 100
      },
      {
        title: '点击率',
        key: 'ctr',
        sorter: true,
        width: 100,
        render(row: any) {
          return row.ctr ? row.ctr + '%' : '-'
        }
      },
      {
        title: '花费',
        key: 'cost',
        sorter: true,
        width: 100
      },
      {
        title: '一键起量消耗',
        key: 'acquisitionCost',
        sorter: true,
        width: 120
      },
      {
        title: '目标转化量',
        key: 'conversionsCount',
        sorter: true,
        width: 120
      },
      {
        title: '目标转化率',
        key: 'conversionsRate',
        sorter: true,
        width: 120,
        render(row: any) {
          return row.conversionsRate ? row.conversionsRate + '%' : '-'
        }
      },
      {
        title: '深度目标转化量',
        key: 'deepConversionsCount',
        sorter: true,
        width: 140
      },
      {
        title: '目标转化成本',
        key: 'conversionsCost',
        sorter: true,
        width: 120
      },
      {
        title: '深度转化成本',
        key: 'deepConversionsCost',
        sorter: true,
        width: 120
      },
      {
        title: '深度目标转化率',
        key: 'deepConversionsRate',
        sorter: true,
        width: 140,
        render(row: any) {
          return row.deepConversionsRate ? row.deepConversionsRate + '%' : '-'
        }
      },
      {
        title: '下单率',
        key: 'orderRate',
        sorter: true,
        width: 120,
        render(row: any) {
          return row.orderRate ? row.orderRate + '%' : '-'
        }
      },
      {
        title: '下单次数',
        key: 'orderPv',
        sorter: true,
        width: 100
      },
      {
        title: '下单ROI',
        key: 'orderRoi',
        sorter: true,
        width: 100
      },
      {
        title: '下单金额',
        key: 'orderAmount',
        sorter: true,
        width: 100
      },
      {
        title: '下单成本',
        key: 'orderCost',
        sorter: true,
        width: 100
      },
      {
        title: '视频号直播预约次数',
        key: 'videoLiveSubscribeCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播观看次数',
        key: 'videoLiveExpCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播观看人数',
        key: 'liveStreamExpUv',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播观看时长',
        key: 'channelsLiveExitPlaDuration',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播点赞次数',
        key: 'videoLiveHeartCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播点赞人数',
        key: 'videoLiveHeartUserCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播评论次数',
        key: 'videoLiveCommentCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播评论人数',
        key: 'videoLiveCommentUserCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播分享次数',
        key: 'videoLiveShareCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播分享人数',
        key: 'videoLiveShareUserCount',
        sorter: true,
        width: 180
      },
      {
        title: '视频号直播商品点击次数',
        key: 'videoLiveCickCommodityCount',
        sorter: true,
        width: 200
      },
      {
        title: '视频号直播商品点击人数',
        key: 'videoLiveClickCommodityUserCount',
        sorter: true,
        width: 200
      },
      {
        title: '视频号直播转化组件曝光次数(气泡)',
        key: 'videoLiveCommodityBubbleExpCount',
        sorter: true,
        width: 260
      },
      {
        title: '视频号直播转化组件点击次数(气泡)',
        key: 'liveStreamCommodityBubbleClkPv',
        sorter: true,
        width: 260
      },
      {
        title: '视频号直播转化组件点击次数(购物袋)',
        key: 'liveStreamCommodityShopBagClkPv',
        sorter: true,
        width: 270
      },
      {
        title: '视频号直播转化组件曝光次数(购物袋)',
        key: 'liveStreamCommodityShopListExpPv',
        sorter: true,
        width: 270
      },
      {
        title: '频号直播间人均观看时长',
        key: 'liveStreamAvgTime',
        sorter: true,
        width: 200
      },
      {
        title: '视频号直播整体观看人数',
        key: 'channelsLiveOutEnterPlaUv',
        sorter: true,
        width: 200
      }
    ]
    const sortArr = [
      {
        type: 'selection',
        key: 'selection',
        fixed: 'left',
        checkedRowKeys: checkedIds.value,
        disabled(row: any) {
          return row.isDeleted === 1
        }
      },
      {
        title: ' ',
        key: 'switch',
        fixed: 'left',
        width: 70,
        render(row: any) {
          return h(NSwitch, {
            value: row.configuredStatus,
            checkedValue: 'AD_STATUS_NORMAL',
            uncheckedValue: 'AD_STATUS_SUSPEND',
            onClick: () => changeStatus(row)
          })
        }
      }
    ]
    showColumnList.value.forEach((item) => {
      arr.forEach((item2) => {
        if (item === item2.key) {
          sortArr.push(item2)
        }
      })
    })
    return sortArr.filter((item) => ['selection', 'switch', ...showColumnList.value].includes(item.key))
  })
  const TableScrollX = computed(() => {
    let x = 20
    columns.value.forEach((item) => {
      if (item.type === 'expand') {
        x += 30
      }
      if (item.type === 'selection') {
        x += 30
      }
      if (item.width) {
        x += item.width
      }
    })
    return x
  })

  onMounted(() => {
    getAccountList()
    gdtAccountOwnerList()
    getCompanyList()
  })

  function handleSorterChange(options: { order: string | number | boolean; columnKey: string }) {
    const sortKey: any = {
      descend: 'desc',
      ascend: 'asc'
    }
    form.value.order = options?.columnKey
    form.value.desc = options.order ? sortKey[options.order] : null
    handleSubmit()
  }
  const handleSubmit = () => {
    immediate.value = true
  }
  const handleRefresh = () => {
    formRef.value.resetFields()
    handleSubmit()
  }
  function handleReload() {
    closeChecked()
    tableRef.value.reload()
  }
  // 清除选中
  function closeChecked() {
    checkedIds.value = []
  }
  const getCompanyList = () => {
    store
      .dispatch('system/mediaAccountMdmNameList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        const list: { value: any; label: any }[] = []
        data.forEach((item: any) => {
          list.push({
            value: item,
            label: item
          })
        })
        companyList.value = list
      })
  }
  const getAccountList = () => {
    store
      .dispatch('system/accountList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        accountList.value = data
      })
  }
  const gdtAccountOwnerList = () => {
    store
      .dispatch('intelligent/gdtAccountOwnerList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        const list: { value: any; label: any }[] = []
        data.forEach((item: any) => {
          list.push({
            value: item,
            label: item
          })
        })
        accountOwnerList.value = list
      })
  }
  // 开关
  const changeStatus = async (row: any) => {
    const params = {
      adgroupList: [{
        accountCode: row.accountCode, //账户ID
        outAdgroupId: row.adgroupId, //腾讯 创意ID
        configuredStatus: row.configuredStatus === 'AD_STATUS_NORMAL' ? 'AD_STATUS_SUSPEND' : 'AD_STATUS_NORMAL' //状态：AD_STATUS_NORMAL-有效;AD_STATUS_SUSPEND-暂停；
      }]
    }
    await store.dispatch('intelligent/gdtAdgroupsBatchStatus', params).then((res) => {})
    tableRef.value.reload()
  }

  const getNowPageData = (val) => {
    nowData.value = val
  }

  const handleCreate = (row: any) => {
    router.push({
      name: 'CreativeCreate',
      query: {
        accountCode: row.accountCode,
        adgroupId: row.adgroupId,
      }
    })
  }
  const handleDetail = (row: any) => {
    adGroupModal.value = {
      show: true,
      row: row
    }
  }
  const handleMedia = (row: any) => {
    router.push({
      name: 'Dashboard',
      query: {
        accountCode: row.accountCode,
        adgroupId: row.adgroupId,
        templateType: 3
      }
    })
  }
</script>

<style lang="scss" scoped></style>
